package com.supcalls;

import cn.hutool.json.JSONUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONConfig;

import java.util.List;

/**
 * Hutool JSONUtil 示例
 */
public class JsonExample {
    public static void main(String[] args) {
        // 1. JSON 字符串转 JSON 对象
        String jsonStr = "{ \"name\": \"张三\", \"age\": 25, \"city\": \"上海\" }";
        JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
        System.out.println("姓名：" + jsonObject.getStr("name"));
        System.out.println("年龄：" + jsonObject.getInt("age"));
        System.out.println("城市：" + jsonObject.getStr("city"));

        // 2. JSON 字符串转 JSON 数组
        String jsonArrayStr = "[{\"name\":\"张三\",\"age\":25}, {\"name\":\"李四\",\"age\":30}]";
        JSONArray jsonArray = JSONUtil.parseArray(jsonArrayStr);
        System.out.println("第一个人的姓名：" + jsonArray.getJSONObject(0).getStr("name"));
        System.out.println("第二个人的年龄：" + jsonArray.getJSONObject(1).getInt("age"));

        // 3. Java 对象转 JSON 字符串
        Person person = new Person("王五", 28, "北京");
        String jsonString = JSONUtil.toJsonStr(person);
        System.out.println("对象转换成 JSON：" + jsonString);

        // 4. JSON 转 Java 对象
        Person parsedPerson = JSONUtil.toBean(jsonString, Person.class);
        System.out.println("反序列化后的对象：" + parsedPerson);

        // 5. JSON 字符串转 List
        List<Person> people = JSONUtil.toList(jsonArray, Person.class);
        System.out.println("List 解析的第一个人的名字：" + people.get(0).getName());

        // 6. 自定义 JSON 配置
        JSONConfig config = new JSONConfig();
        config.setIgnoreNullValue(false); // 是否忽略 null 值
        JSONObject customJson = JSONUtil.parseObj(person, config);
        System.out.println("自定义 JSON：" + customJson);
    }
}

/**
 * Person 类
 */
class Person {
    private String name;
    private int age;
    private String city;

    public Person() {}

    public Person(String name, int age, String city) {
        this.name = name;
        this.age = age;
        this.city = city;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + ", city='" + city + "'}";
    }
}
